import {message, Modal} from 'antd';
import React, {useContext, useEffect, useRef, useState} from 'react';
import style from './index.module.scss';
import {ExclamationCircleFilled} from '@ant-design/icons';
import FormConfig from './form-config.json';
import {ComponentMethods} from '@/types/app';
import {
    getMenuListApi,
    insertMenuApi,
    updateMenuApi,
    deleteMenuApi,
} from '@/api/system/menu';
import {publicArrayToTree} from '@/utils';
import useRenderCom from '@/hooks/useRenderCom';
import {StyleContext} from '@/context/style-context.tsx';
import {TableColumnSlotsProps, TableHeaderProps} from '@/types/table';
import SvgIcon from '@/components/SvgIcon';
import {DynamicFormRef} from "@/types/form";

interface DataType {
    key: React.Key;
    menuName: string;
    menuType: string;
    icon: string | null;
    orderNum: number;
    name: string;
    component: string;
    status: string;
    createTime: string;
}

interface CurMenuType {
    menuId?: number | null;
    menuType?: string;
    isFrame?: number;
    isCache?: number;
    visible?: string;
    status?: string;

    [key: string]: any; // 添加索引签名
}

const SysMenu = () => {
    const {namespace, elNamespace} = useContext(StyleContext);
    const {
        renderForm,
        getFormValue,
        renderDialog,
        renderTable,
        setFormSchema,
        checkFormRequire,
        resetFormValue,
    } = useRenderCom();
    const [loading, setLoading] = useState(false);
    const [buttonIsLoading, setButtonIsLoading] = useState<boolean>(false);
    //表格数据
    const [tableData, setTableData] = useState<DataType[]>([]);
    const menusRef = useRef<CurMenuType[]>([]);
    //当前数据
    const [curMenu, setCurMenu] = useState<CurMenuType>({});
    //form表单ref
    const formRef: any = useRef(null);
    //弹窗表单ref
    const modalFormRef: any = useRef<DynamicFormRef>(null);
    //删除提示
    const [delTip, setDelTip] = useState('是否删除该项？');
    const styleClass = {
        wrapper: `${namespace}-menu-list`,
        container: `${namespace}-menu-list-container`,
    };

    useEffect(() => {
        queryTablePage();
    }, []);
    //搜索点击事件
    const handleSearchClick = () => {
        if (formRef.current) {
            queryTablePage();
        }
    };
    //重置点击事件
    const handleResetClick = () => {
        resetFormValue(formRef.current);
        queryTablePage();
    };

    const handleDialog = (options: any, row?: any) => {
        renderDialog({
            ...options,
            content: renderForm({
                ref: modalFormRef,
                formId: 'dialogForm',
                schema: FormConfig.DialogSchema as any,
                handlers: handlers,
                formList: row ? row : {},
            }),
            onOk: (cb: () => void) => {
                handleConfirm(row, cb);
            },
        });
        setTimeout(() => {
            setFormSchema(modalFormRef.current, [
                {
                    field: 'parentId',
                    path: 'componentProps.treeData',
                    value: menusRef.current,
                },
            ]);
        });
    };

    //新增菜单点击事件
    const handleAddSysMenuClick = (row?: any) => {
        handleDialog(
            {
                title: '新增菜单',
            },
            {
                menuType: row?.menuType || 'M',
                isFrame: '1',
                isCache: 0,
                visible: '0',
                status: '0',
                menuId: null,
                parentId: row?.menuId || null,
            },
        );
    };
    //新增菜单
    const handleConfirm = (row: any, close: () => void) => {
        checkFormRequire(modalFormRef.current).then((values: any) => {
            setButtonIsLoading(true);
            const params = {...values};
            if (row.menuId) {
                params['menuId'] = row.menuId;
            }
            const api = row.menuId ? updateMenuApi : insertMenuApi;
            api(params)
                .then((res: any) => {
                    message.success('操作成功！');
                    queryTablePage();
                })
                .finally(() => {
                    setButtonIsLoading(false);
                    close && close();
                });
        });
    };
    //查询菜单
    const queryTablePage = () => {
        const values = getFormValue(formRef.current);
        getMenuListApi({
            ...values,
            parentId: 0,
        })
            .then((res: any) => {
                const data =
                    res && res.length
                        ? publicArrayToTree({
                            data: res,
                            parentId: res[0].parentId,
                            props: {
                                id: 'menuId',
                            },
                            render: (node: any) => {
                                node['key'] = node['menuId'];
                            },
                        })
                        : [];
                const menus = [
                    {
                        menuName: '主类目',
                        menuId: 0,
                        id: 0,
                        key: 0,
                        parentId: null,
                        children: data,
                    },
                ];
                menusRef.current = menus;
                setTableData(data);
            })
            .finally(() => {
                setLoading(false);
            });
    };
    const onHandleButtonGroup = (options: any) => {
        const {item, row} = options;
        const obj: any = {
            search: handleSearchClick,
            refresh: handleResetClick,
            insertRow: handleAddSysMenuClick,
            editRow: () => {
                handleEditClick(row);
            },
            insertChildRow: () => handleAddSysMenuClick(row),
            deleteRow: () => handleDelClick(row),
        };
        obj[item.field] && obj[item.field]();
    };
    //删除点击事件
    const handleDelClick = (row: any) => {
        setDelTip(row.menuName);
        showDeleteConfirm(row);
    };
    //展示删除确认框
    const showDeleteConfirm = (row: any) => {
        Modal.confirm({
            title: '删除',
            icon: <ExclamationCircleFilled/>,
            content: `是否删除菜单${delTip}？`,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                deleteMenuApi(row.menuId).then(() => {
                    message.success('操作成功！');
                    queryTablePage();
                });
            },
        });
    };
    //编辑
    const handleEditClick = (row: any) => {
        handleDialog(
            {
                title: '编辑菜单',
            },
            row,
        );
    };
    const handlers: ComponentMethods = {
        handleUserChange: (value: any, form: any, item: any) => {
            const zItem = {
                ...curMenu,
            };
            zItem[item.field] = value;
            setCurMenu(zItem);
        },
        handleGenderChange: (item: any) => {
            console.log(item);
        },
        handleButtonGroup: (options: any) => onHandleButtonGroup(options.value),
        handleTableClick: ({value}) => onHandleButtonGroup(value),
    };
    return (
        <div className={style[styleClass.wrapper]}>
            <div className={style[styleClass.container]}>
                <div className={style[`${styleClass.container}-form`]}>
                    {renderForm({
                        ref: formRef,
                        formId: 'filterForm',
                        schema: FormConfig.FilterSchema,
                        handlers: handlers,
                        formList: {},
                    })}
                </div>
                <div className={style[`${styleClass.container}-body`]}>
                    {renderTable<DataType>({
                        tableHeader: FormConfig.TableHeader as any,
                        tableData: tableData,
                        handlers: handlers,
                        isLoading: loading,
                        status: "menuType",
                        slots: {
                            status: ({row, header}) => {
                                const obj: any = {
                                    "0": {
                                        border: "1px solid #d1e9ff",
                                        background: "#e8f4ff",
                                        color: "#155bd4"
                                    },
                                    "1": {
                                        border: "1px solid #ffdbdb",
                                        background: "#ffeded",
                                        color: "#ff4949"
                                    }
                                };
                                return (
                                    <div className={"flex items-center justify-center"}>
                                        <div
                                            className={"flex items-center justify-center"}
                                            style={{
                                                ...obj[row.status],
                                                width: "46px",
                                                borderRadius: "4px",
                                                margin: "0px"
                                            }}
                                        >
                                            {row.status === "0" ? "正常" : "停用"}
                                        </div>
                                    </div>
                                );
                            },
                            icon: ({row, header}: TableColumnSlotsProps) => {
                                return row[header.field] ? (
                                    <SvgIcon
                                        iconClass={row[header.field]}
                                    ></SvgIcon>
                                ) : '--';
                            },
                        },
                    })}
                </div>
            </div>
        </div>
    );
};

export default SysMenu;
